<template>
  <div class="app-container">
    <el-tree
      :data="data5"
      :default-expand-all="true"
      node-key="id"
      draggable
      @node-drop="handleDrop"
      :expand-on-click-node="false"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span class="label_parent">
          <span v-show="node.data.isEdit == 0">{{ data.name }}</span>
          <el-input
            placeholder="请输入章节名称"
            v-show="node.data.isEdit != 0"
            size="mini"
            v-model="node.data.name"
            type="text"
            name="labeltitle"
          />
          <el-button
            size="mini"
            type="text"
            v-show="node.data.isEdit != 0"
            @click="() => finishEdit(node, data)"
          >
            确定
          </el-button>
          <span class="showLabel">
            <el-button type="text" size="mini" @click="() => edit(node, data)">
              修改
            </el-button>
            <el-button type="text" size="mini" @click="() => append(data)">
              添加
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="() => remove(node, data)"
            >
              删除
            </el-button>
          </span>
        </span>
        <span class="fun_block">
          <el-button
            type="text"
            size="mini"
            @click="() => addMovie(node, data)"
          >
            添加视频
          </el-button>
          <el-button type="text" size="mini" @click="() => addTest(node, data)">
            添加测试
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="() => addKnowledgePoints(node, data)"
          >
            关联知识点
          </el-button>
          <el-button type="text" size="mini" @click="() => addFile(node, data)">
            添加资料
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="() => addDiscuss(node, data)"
          >
            添加讨论
          </el-button>
        </span>
      </span>
    </el-tree>
    <el-divider></el-divider>
    <div><el-button type="primary" @click="openone">添加一级</el-button></div>
    <!-- 添加一级章节 -->
    <el-dialog title="章节" :visible.sync="sync" width="600px" append-to-body>
      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item label="章节名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="tijiao">确 定</el-button>
        <el-button type="primary" @click="closeone">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加视频 -->
    <el-dialog
      title="添加视频"
      :visible.sync="videoopen"
      width="600px"
      append-to-body
    >
      <el-upload
        class="upload-demo"
        :action="uploads.url"
        :headers="uploads.headers"
        list-type="picture"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="vsub">确 定</el-button>
        <el-button type="primary" @click="closeone">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加测试 -->
    <el-dialog
      title="添加测试"
      :visible.sync="testopen"
      width="600px"
      append-to-body
    >
      <el-form ref="form" :model="form" label-width="120px"> </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="tsub">确 定</el-button>
        <el-button type="primary" @click="closeone">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 关联知识点 -->
    <el-dialog
      title="关联知识点"
      :visible.sync="knowpointopen"
      width="600px"
      append-to-body
    >
      <el-form ref="form" :model="knowpointform" label-width="120px">
        <!-- 章节选择 -->
        <el-form-item label="章节选择:" prop="courseName">
          <el-cascader
            v-model="knowpointform.chapterId"
            :options="knows"
            :show-all-levels="false"
            :props="{
              expandTrigger: 'hover',
              label: 'name',
              value: 'id',
              emitPath: false,
            }"
          ></el-cascader>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="ksub">确 定</el-button>
        <el-button type="primary" @click="closeone">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加资料 -->
    <el-dialog
      title="关联知识点"
      :visible.sync="fileopen"
      width="600px"
      append-to-body
    >
      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item label="章节名称" prop="name">
          <el-input v-model="filejian" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="资料上传" prop="name">
          <el-upload
            class="upload-demo"
            :action="uploads.url"
            :headers="uploads.headers"
            :file-list="docfiles"
            :limit="1"
            :on-success="ziliaosucc"
            :before-upload="beforeziliao"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="fsub">确 定</el-button>
        <el-button type="primary" @click="closeone">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加讨论 -->
    <el-dialog
      title="关联知识点"
      :visible.sync="discussopen"
      width="600px"
      append-to-body
    >
      <el-form ref="form" :model="form" label-width="120px"> </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dsub">确 定</el-button>
        <el-button type="primary" @click="closeone">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  createChapter,
  updateChapter,
  deleteChapter,
  getChapters,
  getKnowledgeNode,
  relevanceknow,
  getKnowrel,
  uprelknow,
  getfile,
  createfile,
  relfile,
} from "@/api/course";
import { getUserProfile } from "@/api/system/user";
import { getToken } from "@/utils/auth";
let id = 1000;
export default {
  data() {
    const data = [
      {
        id: 1,
        isEdit: 0,
        name: "一级 1",
        children: [
          {
            id: 4,
            isEdit: 0,
            name: "二级 1-1",
            children: [
              {
                id: 9,
                isEdit: 0,
                name: "三级 1-1-1",
              },
              {
                id: 10,
                isEdit: 0,
                name: "三级 1-1-2",
              },
            ],
          },
        ],
      },
      {
        id: 2,
        isEdit: 0,
        name: "一级 2",
        children: [
          {
            id: 5,
            isEdit: 0,
            name: "二级 2-1",
          },
          {
            id: 6,
            isEdit: 0,
            name: "二级 2-2",
          },
        ],
      },
      {
        id: 3,
        isEdit: 0,
        name: "一级 3",
        children: [
          {
            id: 7,
            isEdit: 0,
            name: "二级 3-1",
          },
          {
            id: 8,
            isEdit: 0,
            name: "二级 3-2",
          },
        ],
      },
    ];
    return {
      uploads: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        // 上传的文件列表
        fileList: [],
      },
      userinfo:{},
      filejian: "",
      courseId: 0,
      data5: JSON.parse(JSON.stringify(data)),
      sync: false,
      form: {},
      docfiles: [],
      videoopen: false,
      videoform: {},
      testopen: false,
      testform: {},
      knowpointopen: false,
      knowpointform: {},
      chapterId:"",
      knows: [],
      fileopen: false,
      fileform: {},
      discussopen: false,
      discussform: {},
      upload: {
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        headers: { Authorization: "Bearer " + getToken() },
      },
    };
  },
  mounted: function () {
    this.courseId = this.$route.query.courseId;
    this.getChapters();
    getUserProfile().then(res=>{
      this.userinfo = res.data
    })
  },
  methods: {
    tijiao() {
      this.form.courseId = this.$route.query.courseId;
      this.form.parentId = 0;
      if (this.form.name == "") {
        this.$message.error("内容不可为空");
      } else {
        createChapter(this.form).then((response) => {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.getChapters();
          this.sync = false;
        });
      }
    },
    openone() {
      this.sync = true;
    },
    closeone() {
      this.sync = false;
      this.videoopen = false;
      this.testopen = false;
      this.knowpointopen = false;
      this.fileopen = false;
      this.discussopen = false;
    },
    getChapters() {
      let loadingInstance = this.$loading({
        fullscreen: true,
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      let data = {
        cId: this.courseId,
      };
      getChapters(this.$route.query.courseId).then((response) => {
        for (let i = 0; i < response.data.length; i++) {
          response.data[i].isEdit = 0;
        }
        this.data5 = this.handleTree(response.data, "id");
        const { code, data } = response;
        //console.log("ddd",code, data);
        let data2 = [];
        if (code == 200 && data.length == 0) {
          data2 = [
            {
              id: 0,
              isEdit: 1,
              name: "创建章节，请输入章节表",
              children: [],
            },
          ];
        } else {
          data2 = data;
        }
        // this.data5 = data2;
        loadingInstance.close();
      });
    },
    saveChapters() {
      console.log(this.data5);
    },
    ziliaosucc(res, file) {
      this.fileform.title = file.name;
      this.fileform.matePath = file.response.fileName;
    },
    beforeziliao() {},
    append(data) {
      const newChild = {
        id: 0,
        name: "",
        parentId: data.id,
        isEdit: 1,
        courseId: this.$route.query.courseId,
        children: [],
      };
      if (!data.children) {
        this.$set(data, "children", []);
      }
      data.children.push(newChild);
    },
    edit(node, data) {
      // console.log(node);
      // console.log(data);
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex((d) => d.id === data.id);
      node.data.isEdit = 1;
    },
    finishEdit(node, data) {
      if (data.id == 0) {
        createChapter(data).then((response) => {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.getChapters();
        });
      } else {
        updateChapter(node.data).then((res) => {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.getChapters();
        });
      }

      node.data.isEdit = 0;
      // this.getChapters();
    },
    //添加视频
    addMovie(node, data) {
      console.log(data);
      this.videoopen = true;
    },
    //添加测试
    addTest(node, data) {
      this.testopen = true;
    },
    //添加知识点
    addKnowledgePoints(node, data) {
      this.knowpointform = data;
      getKnowrel({ knowledgeId: data.id }).then((res) => {
        if (res.rows.length == 0) {
          this.knowpointform.isEdits = 0;
        } else {
          this.knowpointform.isEdits = res.rows[0].id;
        }
      });
      getKnowledgeNode({ courseId: this.courseId }).then((res) => {
        this.knows = this.handleTree(res.data, "id");
      });
      this.knowpointopen = true;
    },
    //添加资料
    addFile(node, data) {
      var datas = { chapterId: data.id };
      this.chapterId = data.id
      getfile(datas).then((res) => {
        this.docfiles = res.data;
      });
      this.fileopen = true;
    },
    //添加讨论
    addDiscuss(node, data) {
      this.discussopen = true;
    },
    vsub() {},
    tsub() {},
    ksub() {
      var data = {};
      data.chapterId = this.knowpointform.chapterId;
      data.knowledgeId = this.knowpointform.id;
      if (this.knowpointform.isEdits == 0) {
        relevanceknow(data).then((res) => {
          this.knowpointopen = false;
          this.$message({
            message: "关联成功",
            type: "success",
          });
        });
      } else {
        data.id = this.knowpointform.isEdits;
        uprelknow(data).then((res) => {
          this.knowpointopen = false;
          this.$message({
            message: "关联修改成功",
            type: "success",
          });
        });
      }
    },
    fsub() {
      this.fileform.intro = this.filejian;
      this.fileform.teacherId = this.userinfo.userId;
      this.fileform.type = "文档"
      createfile(this.fileform).then((res) => {
        var data = {chapterId:this.chapterId,materialId:res.data.id};
        relfile(data).then(res=>{
          this.fileopen = false
          this.$message({
            message: "资料添加成功",
            type: "success",
          });
        })

      });
    },
    dsub() {},
    remove(node, data) {
      //要判断是否有子章节
      if (data.children != undefined) {
        if (data.children != undefined || data.children.length > 0) {
          alert("请先删除子章节");
          return;
        }
      }

      deleteChapter(data.id).then((response) => {
        const { code, data } = response;
        if (code == 200) {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.getChapters();
        }
      });
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex((d) => d.id === data.id);
      children.splice(index, 1);
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      //这里是拖拽章节的作用，修改parentId
      //判断移动的节点是哪一个，修改对应的parentId即可
      let parentId = 0;
      if (dropType == "before") {
        //相当于同级目录
        parentId = dropNode.data.parentId;
      }
      if (dropType == "after") {
        parentId = dropNode.data.parentId;
      }
      if (dropType == "inner") {
        //console.log(dropNode)
        parentId = dropNode.data.id;
      }

      draggingNode.data.parentId = parentId;
      updateChapter(draggingNode.data).then((response) => {
        const { code, data } = response;
        if (code == 200) {
          this.getChapters();
        }
      });
      //console.log(draggingNode);
      //console.log('tree drop: ', draggingNode,dropNode,dropNode.parent, dropType,ev);
      //console.log('tree drop: ', draggingNode,dropNode,dropNode.parent, dropType,ev);
    },
    handleAvatarSuccess(res, file) {
      console.log(res);
      // this.imageUrl = URL.createObjectURL(file.raw);
      // updateCourse({ id: this.$route.query.courseId, icon: res.fileName }).then(
      //   (res) => {
      //     console.log(res);
      //   }
      // );
    },
    beforeAvatarUpload(file) {},
  },
};
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  height: 40px;
  flex-direction: row;
}
.showLabel {
  display: none;
  margin-left: 10px;
}
.custom-tree-node:hover .showLabel {
  display: block;
}
.fun_block {
  display: flex;
}
.label_parent {
  display: flex;
  flex-direction: row;
  align-items: center;
  font-size: 14px;
  padding-right: 8px;
  flex-direction: row;
  padding-bottom: 5px;
  padding-top: 5px;
}
.el-tree-node__content {
  height: 60px;
}
</style>
